﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using CaptchaMVC.Attribute;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.RelyingParty;
using ORM.Business.Feedbacks;
using ORM.Business.Interfaces;
//using ORM.Business.Models.Caching;
using ORM.Business.Models;
using ORM.Business.Models.Caching;
using ORM.Business.Models.Entities;
using ORM.Common;
using ORM.Common.Logging;
using ORM.Framework.Filters;
using ORM.Models.FileManagement;
using ORM.Resources;
using ORM.ViewModels;
using ORM.ViewModels.Account;
//using ORM.Web.Framework.Filters;
//using ORM.ViewModels.Account;
//using ORM.Common.Logging;
//using ORM.Resources;
//using ORM.Web.Framework.Filters;
using ORM.Framework.Security;
using ORM.Web.Models;
using ORM.Web.ViewModels.Account;

//using ORM.Web.Models;
//using ORM.Web.Models.FileManagement;
//using ORM.Web.ViewModels.Account;
//using DotNetOpenAuth.Messaging;
//using DotNetOpenAuth.OpenId;
//using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
//using DotNetOpenAuth.OpenId.RelyingParty;

namespace ORM.Controllers
{
    public class AccountController : FrontEndControllerBase
    {

        #region Variables

        public ISecurityRepository _securityRepository;
        private IUserRepository _userRepository;
        private IUploadHandler _uploadHandler;
        private IFileManager _fileManager;
        private IGuideRepository _guideRepository;
        private IQuestionRepository _questionRepository;
        private OrmEntities OrmDBContext = new OrmEntities(); 
        #endregion

        //#region Constructor

        public AccountController(
            ISecurityRepository securityRepository,
            IUserRepository userRepository,
            IUploadHandler uploadHandler,
            IFileManager fileManager,
            IGuideRepository guideRepository,
            IQuestionRepository questionRepository
            )
        {
            _securityRepository = securityRepository;
            _fileManager = fileManager;
            _uploadHandler = uploadHandler;
            _userRepository = userRepository;
            _guideRepository = guideRepository;
            _questionRepository = questionRepository;
        }

        //#endregion

       
        #region Login Methods

        public ActionResult Login(string returnUrl)
        {

            returnUrl = Request.QueryString["ReturnUrl"];
            // If already logged in
            if (Request.IsAuthenticated)
            {
                if (Url.IsLocalUrl(returnUrl))
                    return Redirect(returnUrl);
                else
                    return RedirectToAction("Index", "Home");
            }
            //this.TempData["ReturnUrl"] = returnUrl;
            return View();
          //  return PartialView("Login");
        }

        /// <summary>
        /// Login by website account
        /// </summary>
        /// 
        public ActionResult table()
        {
            string Name = Request["SearchText"];
            return View();
        }
        //----------------------------------------------------------------------------------------------------
        [HttpPost]
        public ActionResult table(FormCollection col)
        {
            string UserName = Request["UserName"];
            string PassWord = Request["PassWord"];
            LoginViewModel vm = new LoginViewModel();
            vm.Username = UserName;
            vm.Password = PassWord;
            String returnUrl = "";
            bool check = Login1(vm, returnUrl);
            if (check == false)
            {
                ViewBag.check1 = "sai";
                return View();
            }
            else
            {
                ViewBag.check1 = "ok";
                ViewBag.username = UserName;
                //return View("Index", "Home");
                return View();
            }
            return RedirectToAction("Index", "Home");
        }
        public bool Login1(LoginViewModel model, string returnUrl)
        {
            //if (Request.IsAuthenticated)
            //{
            //    ViewBag.UserNameLogin = model.Username;
            //    if (Url.IsLocalUrl(returnUrl))
            //        return Redirect(returnUrl);
            //    else
            //        //return RedirectToAction("Index", "Home");
            //}

            if (ModelState.IsValid)
            {
                Feedback feedback = _securityRepository.Login(model.Username, model.Password);
                //if (Membership.ValidateUser(model.Username, model.Password))
                //{
                if (feedback.Success)
                {
                    //if (Membership.ValidateUser(model.Username, model.Password))
                    //{

                    FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);
                    ViewBag.UserNameLogin = model.Username;
                    //return (View());
                    if (Url.IsLocalUrl(returnUrl))
                        //return Redirect(returnUrl);
                        return true;
                    else
                        //return RedirectToAction("Index", "Home");
                        return true;
                }
                //}
                else
                {
                    ModelState.AddModelError("", feedback.Message);
                    return false;
                }
            }
            return false;
            //return View("Views/Shared/_LogOnPartial.cshtml");
        }
        [HttpPost]
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            //string url = this.TempData["ReturnUrl"].ToString();
            // If already logged in
           // returnUrl = Request.RawUrl;
            if (Request.IsAuthenticated)
            {
                ViewBag.UserNameLogin = model.Username;
                if (Url.IsLocalUrl(returnUrl))
                    return Redirect(returnUrl);
                else
                    return RedirectToAction("Index", "Home");
            }

            if (ModelState.IsValid)
            {
                Feedback feedback = _securityRepository.Login(model.Username, model.Password);            
                if (feedback.Success)
                {                   
                    FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);
                    ViewBag.UserNameLogin = model.Username;
                    //return (View());
                    if (Url.IsLocalUrl(returnUrl))
                        return Redirect(returnUrl);
                    else
                    {
                        return RedirectToAction("Index", "Home");  
                    }                        
                }                
                else
                {                    
                    ModelState.AddModelError("", feedback.Message);
                    ViewBag.check1 = "sai";
                    return View();                   
                }
            }
            return View(model);            
        }

        [AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get), ValidateInput(false)]
        public ActionResult OpenIdLogOn(string returnUrl)
        {
            // If already logged in
            if (Request.IsAuthenticated)
            {
                if (Url.IsLocalUrl(returnUrl))
                    return Redirect(returnUrl);
                else
                    return RedirectToAction("Index", "Home");
            }

            var openid = new OpenIdRelyingParty();
            var response = openid.GetResponse();

            if (response == null)  // Initial operation
            {
                // Send the request to the OpenId provider server
                Identifier id;
                if (Identifier.TryParse(Request.Form["openid_identifier"], out id))
                {
                    try
                    {
                        IAuthenticationRequest request = openid.CreateRequest(Identifier.Parse(Request.Form["openid_identifier"]));
                        var fields = new ClaimsRequest { Email = DemandLevel.Require, FullName = DemandLevel.Require };
                        request.AddExtension(fields);
                        return request.RedirectingResponse.AsActionResult();
                    }
                    catch (ProtocolException ex)
                    {
                        Logger.Error(ex);
                        // display error by showing original LogOn view
                        ModelState.AddModelError("", "Đăng nhập không thành công!");
                        return View("Login");
                    }
                }
                else
                {
                    // display error by showing original LogOn view
                    ModelState.AddModelError("", "Đăng nhập không thành công!");
                    return View("Login");
                }
            }
            else
            {
                // OpenID Provider sending assertion response
                switch (response.Status)
                {
                    case AuthenticationStatus.Authenticated:
                        string identifier = response.ClaimedIdentifier;
                        var claimUntrusted = response.GetUntrustedExtension<ClaimsResponse>();
                        var claim = response.GetExtension<ClaimsResponse>();

                        user user = null;

                        if (claim != null)
                        {
                            user = new user
                                       {
                                           Email = claim.Email,
                                           Username = claim.FullName,
                                           SocialNetworkUrl = identifier
                                       };
                        }

                        //fallback to claim untrusted, as some OpenId providers may not
                        //provide the trusted ClaimsResponse, so we have to fallback to 
                        //trying the untrusted on
                        if (claimUntrusted != null && user == null)
                        {
                            user = new user
                                       {
                                           Email = claimUntrusted.Email,
                                          Username = claimUntrusted.FullName,
                                           SocialNetworkUrl = identifier
                                       };
                        }

                        //Register user and store Forms Authorisation cookie 
                        if (LoginByOpenId(user))
                        {
                            if (Url.IsLocalUrl(returnUrl))
                                return Redirect(returnUrl);
                            else
                                return RedirectToAction("Index", "Home");
                        }
                        else
                        {
                            return View("Login");
                        }
                        
                    case AuthenticationStatus.Canceled:
                        ModelState.AddModelError("", "Đăng nhập không thành công!");
                        return View("Login");
                    case AuthenticationStatus.Failed:
                        ModelState.AddModelError("", "Đăng nhập không thành công!");
                        return View("Login");
                }
            }

            return new EmptyResult();
        }

       
       
        #endregion

        [PermissionAuthorize]
        public ActionResult LogOff(string returnUrl)
        {
            Session.Abandon();
            FormsAuthentication.SignOut();
            SecurityCacheManager.RemovePrincipal(CurrentUser.UserInfo.Username);
            if (Url.IsLocalUrl(returnUrl))
                return Redirect(returnUrl);
            else
                return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register
        #region Register Methods
        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        [CaptchaVerify("Ký tự nhập không đúng")]
        public ActionResult Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var newUser = new user
                {
                    Email = model.Email,
                    Username = model.Username,
                    Password = model.Password
                };

                Feedback feedback = _securityRepository.Register(newUser);

                if (feedback.Success)
                {
                    // Send welcome email to user
                    MailController mailController = new MailController();
                    try
                    {
                        mailController.WelcomeEmail(model).Deliver();
                    }
                    catch
                    {
                        //  SetMessage("Có lỗi xảy ra. Hệ thống không thể gửi mail chúc mừng cho bạn.", MessageType.Error);
                    }
                    return View("WelcomeEmail", model);
                }
                else
                {
                    ModelState.AddModelError("", feedback.Message);
                }
            }

            return View(model);
        }
        #endregion
        //
        // GET: /Account/ChangePassword
        #region Change Password Methods

        [PermissionAuthorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        [HttpPost]
        [PermissionAuthorize]
        public ActionResult ChangePassword(ChangePasswordViewModel vm)
        {
            if (ModelState.IsValid)
            {
                var feeback = _securityRepository.ChangePassword(vm.OldPassword, vm.NewPassword, CurrentUser.UserInfo.Id);

                if (feeback.Success)
                {
                   // SetMessage(Messages.UpdatePasswordSuccess, MessageType.Success);
                    //return View(vm);
                    ViewBag.MchangePassSuccess = "ok";
                    //return View("~/Views/home/index.cshtml");
                    return View();
                }
                else
                {
                    ViewBag.ErrorMessage = feeback.Message;
                      // SetMessage(feeback.Message, MessageType.Error);
                    return View(vm);
                }
            }

           // SetMessage(Messages.UpdatePasswordFail, MessageType.Error);
            return View(vm);
        }

        [PermissionAuthorize]
        public ActionResult CancelChangePassword()
        {
            return RedirectToAction("Profile", "Account");
        }

        #endregion

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }


        public ActionResult EditUserInformation()
        {
            object vm = GetPersonalInfo();
            return View(vm);
        }
        [HttpPost]
        [PermissionAuthorize]
        public ActionResult EditUserInformation(UpdateUserProfileViewModel vm)
        {
            

            object viewmodel = null;
           // var feedback = _userRepository.GetPersonalInfo(vm.User.Id);
            if (ModelState.IsValid)
            {
                vm.User.Id = CurrentUser.UserInfo.Id;
                string newUrl = null;

                if (vm.File != null)
                {
                    var uploadFeedback = _uploadHandler.UploadUserAvatar(CurrentUser.UserInfo.Id, vm.File);
                    if (!uploadFeedback.Success)
                    {
                        string msg = string.Format("Cập nhật ảnh đại diện không thành công. Chỉ hỗ trợ ảnh định dạng JPG và PNG. " +
                              "Kích thước ảnh không được vượt quá {0}Mb. Nếu lỗi vẫn xảy ra bạn hãy thử lại vào lúc khác.",
                              AppConfigs.UploadImageMaxSize);
                        SetMessage(msg, MessageType.Error);
                        viewmodel = GetPersonalInfo();
                        ViewBag.UploadImageError = msg;
                        return View(viewmodel);
                    }

                    newUrl = string.Format("{0}{1}{2}", uploadFeedback.Data[0], ORM.Common.Constants.ImageUrlsSeparator,
                                                  uploadFeedback.Data[1]);
                    vm.User.AvatarUrl = newUrl;
                    CurrentUser.UserInfo.AvatarUrl = newUrl;
                }

                var feedback = _userRepository.UpdateUserProfile(vm.User);
                ViewBag.EMessage = "1";
                if (feedback.Success)
                {
                    //SetMessage(Messages.UpdateUserProfileSuccess, MessageType.Success);

                    // Delete old avatar files
                    if (!string.IsNullOrEmpty(feedback.Data))
                        _fileManager.DeleteImagePair(feedback.Data);
                    viewmodel = GetPersonalInfo();
                    ViewBag.EMessage= "2";
                 //   SecurityCacheManager.GetPrincipal(CurrentUser.UserInfo.Username).UserInfo.Username = CurrentUser.UserInfo.Username;
                   // Session.Abandon();
                   // SecurityCacheManager.RemovePrincipal(CurrentUser.UserInfo.Username);
                    SecurityCacheManager.GetPrincipal(CurrentUser.UserInfo.Username).UserInfo.Username = CurrentUser.UserInfo.Username;                 
                    return View(viewmodel);
                   
                }
                else
                {
                    // If update to DB unsuccessfully, delete new avatar files
                    if (!string.IsNullOrEmpty(newUrl))
                        _fileManager.DeleteImagePair(newUrl);
                }
            }

            SetMessage(Messages.UpdateInformationFail, MessageType.Error);
            viewmodel = GetPersonalInfo();
            return View(viewmodel);
            
        }

        #region Reset Password Methods

        public ActionResult RequestResetPassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult RequestResetPassword(RequestResetPasswordViewModel vm)
        {
            if (ModelState.IsValid)
            {
                // Insert ResetPassword key into DB
                var tmp = string.Format("{0}{1}", Guid.NewGuid(), Guid.NewGuid());
                var resetPasswordKey = tmp.Replace("-", "");

                var feedback = _securityRepository.RequestResetPassword(vm.Email, resetPasswordKey);
                if (feedback.Success)
                {
                    // Send verification email
                    MailController mailController = new MailController();
                    vm.Username = feedback.Data.Username;
                    vm.ResetPasswordKey = resetPasswordKey;
                    vm.ResetPasswordLink = string.Format("http://{0}/account/resetpassword?key={1}", Request.Url.Authority,
                                                        resetPasswordKey);
                    try
                    {
                        mailController.ResetPasswordVerificationEmail(vm).Deliver();

                        return View("RequestPasswordSuccess");
                    }
                    catch
                    {
                        //SetMessage("Có lỗi xảy ra. Hệ thống không thể gửi mail xác nhận quên mật khẩu cho bạn.", MessageType.Error);
                    }
                }
                else
                {
                    ModelState.AddModelError("", feedback.Message);
                }
            }

            return View(vm);
        }

        public ActionResult ResetPassword()
        {
            // Get key in query string
            var resetPasswordKey = Request.QueryString["key"];
            if (!string.IsNullOrEmpty(resetPasswordKey))
            {
                var feeback = _securityRepository.CheckResetPasswordKey(resetPasswordKey);
                if (feeback.Success)
                    return View();
            }

            return View("IncorrectResetPasswordKey");
        }

        [HttpPost]
        public ActionResult ResetPassword(ResetPasswordViewModel vm)
        {
            if (!ModelState.IsValid)
                return View(vm);

            // Get key in query string
            var resetPasswordKey = Request.QueryString["key"];
            if (!string.IsNullOrEmpty(resetPasswordKey))
            {
                // Get requested email
                var checkFeeback = _securityRepository.SetResetPasswordKey(resetPasswordKey);
                if (!checkFeeback.Success)
                    return View("IncorrectResetPasswordKey");

                var feedback = _securityRepository.ResetPassword(checkFeeback.Data.Email, vm.Password);
                if (feedback.Success)
                {
                    return View("ResetPasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", feedback.Message);
                    return View(vm);
                }
            }
            else
            {
                return View("IncorrectResetPasswordKey");
            }
        }

        #endregion
        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion

        #region Unauthorized

        public ActionResult Unauthorized()
        {
            SetMessage(Messages.Unauthorized, MessageType.Error);
            return View();
        }

        #endregion

        #region Update User Profile Methods

        [PermissionAuthorize]
        public ActionResult Profile()
        {
            ProfileViewModel vm = new ProfileViewModel
                                      {
                                          User = OrmDBContext.Users.Find(CurrentUser.UserInfo.Id),
                                          CreatedGuide = OrmDBContext.Guides.Where(g => g.PostedBy == CurrentUser.UserInfo.Id & !g.IsDeleted).OrderByDescending(g => g.PostedDate).ToList(),
                                          CreatedQuestion = OrmDBContext.Questions.Where(g => g.PostedById == CurrentUser.UserInfo.Id & !g.IsDeleted).OrderByDescending(g => g.PostedDate).ToList(),
                                          GuideBookmarks = _guideRepository.GetGuideBookmarks(CurrentUser.UserInfo.Id).Data,
                                          QuestionBookmarks = _questionRepository.GetQuestionBookmarks(CurrentUser.UserInfo.Id).Data,
                                      };
            
            return View(vm);
        }

        //[HttpPost]

      

        public ActionResult GetAllUser(string usernameSearch)
        {                 
            ListUserViewModel vm = new ListUserViewModel();
            var feedback = _userRepository.GetSimilarUsers(usernameSearch);
            if (feedback.Success)
            {
                vm.UsernameSearch = usernameSearch;
                vm.Users = feedback.Data;  
            }
            else
            {
                SetMessage(feedback.Message, MessageType.Error);
            }
            return View(vm);

        }
        //----------------------------------------------------------------------------------
        //public ActionResult GetAllUser(PageInfo pageInfo,int pageNo =1)
        //{
        //    ListUserViewModel vm = null;
        //    List<user> userList = new List<user>();
        //    var pageInfo = new PageInfo(Convert.ToInt16(ConfigurationManager.AppSettings["QuestionsPageSize"]), pageNo);
        //    var feedback = _userRepository.GetAllUsers(pageInfo);
        //    if (feedback.Success)
        //    {
        //        return View(feedback.Data);
        //    }

        //    return View(new List<user>());
        //}
        //----------------------------------------------------------------------------------
        //[HttpPost]
        //public ActionResult Profile(UpdateUserProfileViewModel vm)
        //{
        //    var feedback = _userRepository.GetPersonalInfo(vm.User.Id);
        //    if(feedback.Success)
        //    {
        //        return View(vm);
        //    }
        //    else
        //    {
        //        SetMessage(feedback.Message, MessageType.Error);
        //        return View(vm);
        //    }
        //    return View(vm);
        //}
        //[HttpPost]
        //public ActionResult Profile(UpdateUserProfileViewModel vm)
        //{
        //    object viewmodel = null;
        //    //var feedback = _userRepository.GetPersonalInfo(vm.User.Id);
        //    if (ModelState.IsValid)
        //    {
        //        vm.User.Id = CurrentUser.UserInfo.Id;
        //        string newUrl = null;

        //        if (vm.File != null)
        //        {
        //            var uploadFeedback = _uploadHandler.UploadUserAvatar(CurrentUser.UserInfo.Id, vm.File);
        //            if (!uploadFeedback.Success)
        //            {
        //                string msg = string.Format("Cập nhật ảnh đại diện không thành công. Chỉ hỗ trợ ảnh định dạng JPG và PNG. " +
        //                      "Kích thước ảnh không được vượt quá {0}Mb. Nếu lỗi vẫn xảy ra bạn hãy thử lại vào lúc khác.",
        //                      AppConfigs.UploadImageMaxSize);
        //                SetMessage(msg, MessageType.Error);
        //                viewmodel = GetPersonalInfo();
        //                return View(viewmodel);
        //            }

        //            newUrl = string.Format("{0}{1}{2}", uploadFeedback.Data[0], ORM.Common.Constants.ImageUrlsSeparator,
        //                                          uploadFeedback.Data[1]);
        //            vm.User.AvatarUrl = newUrl;
        //            CurrentUser.UserInfo.AvatarUrl = newUrl;
        //        }

        //        var feedback = _userRepository.UpdateUserProfile(vm.User);

        //        if (feedback.Success)
        //        {
        //            SetMessage(Messages.UpdateUserProfileSuccess, MessageType.Success);

        //            // Delete old avatar files
        //            if (!string.IsNullOrEmpty(feedback.Data))
        //                _fileManager.DeleteImagePair(feedback.Data);
        //            viewmodel = GetPersonalInfo();
        //            return View(viewmodel);
        //        }
        //        else
        //        {
        //            // If update to DB unsuccessfully, delete new avatar files
        //            if (!string.IsNullOrEmpty(newUrl))
        //                _fileManager.DeleteImagePair(newUrl);
        //        }
        //    }

        //    SetMessage(Messages.UpdateInformationFail, MessageType.Error);
        //    viewmodel = GetPersonalInfo();
        //    return View(viewmodel);
        //}
       

       
        [PermissionAuthorize]
        public ActionResult GetTabDetails(int id = 0)
        {
            string viewName = string.Empty;
            object viewModel = null;
            switch (id)
            {
                case 1:
                    viewName = "_UserDetailsInformation";
                    viewModel = GetPersonalInfo();
                    break;
                case 2:
                    viewName = "_EditUserInformation";
                    viewModel = GetPersonalInfo();
                    break;
                //case 3:
                //    viewName = "_UserRecipe";
                //    viewModel = GetUserRecipe(CurrentUser.UserInfo.Id);
                //    break;
                //case 4:
                //    viewName = "_UserTip";
                //    viewModel = GetUserTip(CurrentUser.UserInfo.Id);
                //    break;
                //case 5:
                //    viewName = "_UserNews";
                //    viewModel = GetUserNews(CurrentUser.UserInfo.Id);
                //    break;
                //case 6:
                //    viewName = "_UserQuestion";
                //    viewModel = GetUserQuestion(CurrentUser.UserInfo.Id);
                //    break;
                //case 7:
                //    viewName = "_UserAnswer";
                //    viewModel = GetUserAnswer(CurrentUser.UserInfo.Id);
                //    break;
                //case 8:
                //    viewName = "_UserFavoriteRecipe";
                //    viewModel = GetUserFavoriteRecipe(CurrentUser.UserInfo.Id);
                //    break;
                case 9:
                    viewName = "_StatisticInformation";
                    viewModel = GetPersonalInfo();
                    break;
            }

            return PartialView(viewName, viewModel);
        }

        [HttpPost]
        [PermissionAuthorize]
        public JsonResult RemoveUserAvatar()
        {
            var feedback = _userRepository.RemoveAvatar(CurrentUser.UserInfo.Id);

            if (feedback.Success)
            {
                CurrentUser.UserInfo.AvatarUrl = null;

                // Delete old avatar files
                if (!string.IsNullOrEmpty(feedback.Data))
                    _fileManager.DeleteImagePair(feedback.Data);

                // Construct anonymous avatar url to return
                UrlHelper urlHelper = new UrlHelper(Request.RequestContext);
                var path = AppConfigs.AvatarFolderPath + Common.Constants.AnonymousAvatar;

                return Json(new
                {
                    Success = true,
                    AnonymousAvatar = urlHelper.Content(path)
                });
            }

            return Json(feedback);
        }

        public ActionResult Details(int id = 0)
        {
            if (CurrentUser != null)
            {
                if (id == CurrentUser.UserInfo.Id)
                    return RedirectToAction("Profile", "Account");
            }

            ProfileViewModel vm = new ProfileViewModel
            {
                User = OrmDBContext.Users.First(u => !u.IsDeleted && u.Id == id),
                CreatedGuide = OrmDBContext.Guides.Where(g => g.PostedBy == id & !g.IsDeleted).OrderByDescending(g => g.PostedDate).ToList(),
                CreatedQuestion = OrmDBContext.Questions.Where(g => g.PostedById == id & !g.IsDeleted).OrderByDescending(g => g.PostedDate).ToList(),
            };

            return View(vm);
        }

        #endregion

        private object GetPersonalInfo()
        {
            var feedback = _userRepository.GetPersonalInfo(CurrentUser.UserInfo.Id);

            if (feedback.Success)
            {
                return new UpdateUserProfileViewModel
                {
                    User = feedback.Data,
                    Locations = PrepareLocations()
                };
            }

            return "Có lỗi xảy ra. Lấy thông tin cá nhân không thành công.";
        }

        private object GetUserDetailsInfo(int id)
        {
            var feedback = _userRepository.ViewOtherUserInformaton(id);

            if (feedback.Success)
            {
                return new UpdateUserProfileViewModel
                {
                    User = feedback.Data
                };
            }

            SetMessage(feedback.Message, MessageType.Error);
            return null;
        }
        [PermissionAuthorize]
        public ActionResult Notification()
        {
            var getCommentNotificationQuery = from c in OrmDBContext.GuideComments
                                              join g in OrmDBContext.Guides on c.GuideId equals g.Id
                                              orderby c.PostedDate descending
                                              where
                                                  !c.IsDeleted && !g.IsDeleted &&
                                                  g.PostedBy == CurrentUser.UserInfo.Id &&
                                                  c.PostedBy != CurrentUser.UserInfo.Id &&
                                                  !c.IsReadByGuideAuthor
                                              select c;
            var getAnswerNotificationQuery = from a in OrmDBContext.Answers
                                             join q in OrmDBContext.Questions on a.QuestionId equals q.Id
                                             orderby a.PostedDate descending
                                             where
                                                 !a.IsDeleted && a.IsApproved && !q.IsDeleted &&
                                                 q.PostedById == CurrentUser.UserInfo.Id &&
                                                 a.PostedById != CurrentUser.UserInfo.Id &&
                                                 !a.IsReadByQuestioner
                                             select a;
            NotificationViewModel vm = new NotificationViewModel
                                           {
                                               Comments = getCommentNotificationQuery.ToList(),
                                               Answers = getAnswerNotificationQuery.ToList()
                                           };
            return View(vm);
        }

        private IList<Location> PrepareLocations()
        {
            var locations = ReferenceDataCache.LocationCollection.ToList();
            return locations;
        }

         private bool LoginByOpenId(user user)
        {
            var feedback = _securityRepository.LoginByOpenId(user);

            if (feedback.Success)
            {
                FormsAuthentication.SetAuthCookie(feedback.Data.Username, true);

                // If this is the first times user logged in by this account --> send welcome mail
                if (!feedback.Data.IsLoggedIn)
                {
                    MailController mailController = new MailController();
                           mailController.WelcomeEmailUserOpenId(feedback.Data).Deliver();
                     // Send welcome email to user
               
                }
            }
            else
            {
                ModelState.AddModelError("", feedback.Message);
            }

            return feedback.Success;
        }
    }
}
